#include "paymentpage.h"
#include "ui_paymentpage.h"
#include <QTableWidget>
#include <QJsonArray>
#include <QHeaderView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include "protocol.h"
#include "tools.h"

PaymentPage::PaymentPage(QWidget *parent, QTcpSocket *externalSocket) :
    QWidget(parent),
    ui(new Ui::PaymentPage),
    socket(externalSocket)
{
    ui->setupUi(this);

    tableWidget = new QTableWidget(this);
    refreshButton = new QPushButton("刷新", this);
    exportButton = new QPushButton("导出", this);

    // 表格列数与表头
    tableWidget->setColumnCount(4);
    tableWidget->setHorizontalHeaderLabels(QStringList() << "车牌号" << "支付时间" << "费用" << "停车记录" );

    // 表格设置自适应列宽
    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 表格设置最小大小
    tableWidget->setMinimumSize(600, 400);

    // 创建按钮的水平布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(refreshButton);
    buttonLayout->addWidget(exportButton);
    buttonLayout->addStretch();  // 挤到左边，右边留空白

    // 创建整体垂直布局
    mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(tableWidget);

    // 设置窗口使用这个layout
    this->setLayout(mainLayout);
    connect(refreshButton, &QPushButton::clicked, this, &PaymentPage::onRefreshClicked);
    connect(exportButton, &QPushButton::clicked, this, &PaymentPage::onExportClicked);
}

PaymentPage::~PaymentPage()
{
    delete ui;
}

void PaymentPage::onRefreshClicked()
{
    int lines = countLinesInFile("payment_records.txt")-1;
    QJsonObject root;
    QJsonObject message1;
    QJsonObject message2;
    root["func"] = 10;
    //message["signal"] = 1;
    message2["message2"] = message1;
    message2["lines"] = lines;
    root["message"] = message2;

    QByteArray dataToSend = Encode(root);
    socket->write(dataToSend);
}

void PaymentPage::onExportClicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, "保存文件", "支付记录表.csv", "CSV文件 (*.csv)");
      if (fileName.isEmpty()) {
          return;  // 用户取消保存
      }

      QFile file(fileName);
      if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
          qDebug() << "无法打开文件:" << file.errorString();
          return;
      }

      QTextStream out(&file);

      // 写表头
      QStringList headers;
      for (int col = 0; col < tableWidget->columnCount(); ++col) {
          headers << tableWidget->horizontalHeaderItem(col)->text();
      }
      out << headers.join(",") << "\n";

      // 写表格数据
      for (int row = 0; row < tableWidget->rowCount(); ++row) {
          QStringList rowData;
          for (int col = 0; col < tableWidget->columnCount(); ++col) {
              QTableWidgetItem *item = tableWidget->item(row, col);
              if (item) {
                  rowData << item->text();
              } else {
                  rowData << "";  // 如果空，写空字符串
              }
          }
          out << rowData.join(",") << "\n";
      }

      file.close();
      qDebug() << "导出成功:" << fileName;
}
/*
void PaymentPage::handleServerMessage(const QJsonObject &jsonObject)
{
    tableWidget->setColumnCount(4);
    tableWidget->setHorizontalHeaderLabels(QStringList() <<  "车牌号" << "支付时间" << "费用" << "停车记录" );

    QJsonArray messages = jsonObject["messageArray"].toArray();

    qDebug()<<"QJsonArray messages:"<<messages;
    tableWidget->setRowCount(messages.size());

    for (int i = 0; i < messages.size(); ++i) {
        QJsonObject obj = messages[i].toObject();
        qDebug()<<"obj:"<<obj;
        QString plate = obj["plate"].toString();
        QString payment_time = obj["payment_time"].toString();
        QString amount = obj["amount"].toString();
        QString record_id = obj["record_id"].toString();

        tableWidget->setItem(i, 0, new QTableWidgetItem(QString::fromUtf8(plate.toUtf8())));
        tableWidget->setItem(i, 1, new QTableWidgetItem(payment_time));
        tableWidget->setItem(i, 2, new QTableWidgetItem(amount));
        tableWidget->setItem(i, 3, new QTableWidgetItem(record_id));
    }
    // 可选：自适应列宽
    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tableWidget->show();
}
*/

void PaymentPage::handleServerMessage(const QJsonObject &jsonObject)
{
    int isChanged = jsonObject["isChanged"].toInt();
    //int lines = countLinesInFile("payment_records.txt")-1;
    loadPaymentRecordsFromFile();

    if(!isChanged)
    {
        qDebug()<<"no new data,load from local";
        return;
    }

    qDebug()<<"append new data from server";
    QJsonValue jsonObject2 = jsonObject["message2"].toObject();
    QJsonArray messages = jsonObject2["messageArray"].toArray();
    qDebug() << "QJsonArray messages:" << messages;

    // 获取当前已有的行数
    int currentRowCount = tableWidget->rowCount();
    tableWidget->setRowCount(currentRowCount + messages.size());


    QFile file("payment_records.txt");
    if (file.open(QIODevice::Append | QIODevice::Text)) {   //追加模式写入
        QTextStream out(&file);
        out.setCodec("UTF-8");

        for (int i = 0; i < messages.size(); ++i) {
            QJsonObject obj = messages[i].toObject();
            QString plate = obj["plate"].toString();
            QString payment_time = obj["payment_time"].toString();
            QString amount = obj["amount"].toString();
            QString record_id = obj["record_id"].toString();

            int row = currentRowCount + i;
            tableWidget->setItem(row, 0, new QTableWidgetItem(plate));
            tableWidget->setItem(row, 1, new QTableWidgetItem(payment_time));
            tableWidget->setItem(row, 2, new QTableWidgetItem(amount));
            tableWidget->setItem(row, 3, new QTableWidgetItem(record_id));

            out << plate << "\t\t" << payment_time << "\t\t" << amount << "\t\t" << record_id << "\n";
        }

        file.close();
    } else {
        qWarning() << "无法打开文件进行写入！";
    }

    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tableWidget->show();
}

void PaymentPage::loadPaymentRecordsFromFile()
{
    QFile file("payment_records.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开文件读取数据！";
        return;
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");

    QStringList dataLines;
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (!line.isEmpty()) {
            dataLines.append(line);
        }
    }

    file.close();

    if (dataLines.size() <= 1) {
        qWarning() << "没有有效的数据行可加载！";
        return;
    }

    // 设置表头
    tableWidget->setColumnCount(4);
    tableWidget->setHorizontalHeaderLabels(QStringList() << "车牌号" << "支付时间" << "费用" << "停车记录");

    // 除去第一行表头，从第二行开始处理
    int rowCount = dataLines.size() - 1;
    tableWidget->setRowCount(rowCount);

    for (int i = 1; i < dataLines.size(); ++i) {
        QStringList fields = dataLines[i].split("\t\t");
        if (fields.size() != 4) {
            qWarning() << "第" << i << "行字段数异常：" << fields;
            continue;
        }
        for (int j = 0; j < 4; ++j) {
            tableWidget->setItem(i - 1, j, new QTableWidgetItem(fields[j].trimmed()));
        }
    }

    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tableWidget->show();
}

